package org.skyui.validators;

import java.util.ArrayList;

import org.skyui.beanmanagers.BeanSetManager;

import com.baycrypt.server.beans.people.UserBean;
import com.vaadin.data.Validator;
import com.vaadin.data.validator.EmailValidator;
import com.vaadin.data.validator.RegexpValidator;
import com.vaadin.data.validator.StringLengthValidator;

public class Validators {

	private static boolean isInited = false;


	private static String _255 = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";





	public static class BeanExistsValidator implements Validator {

		private BeanSetManager beanManager;

		private BeanExistsValidator(BeanSetManager beanManager) {
			if (beanManager == null)
				throw new java.lang.IllegalArgumentException("Null beanmanager");
			this.beanManager = beanManager;
		}


		public boolean isValid(Object value) {
			return this.beanManager.getBeanByPrimaryAttribute((String) value) == null;
		}

		public void validate(Object value) throws InvalidValueException {
			if (!isValid(value))
				throw new InvalidValueException(
						"This username is already taken.");
		}

	}

	public static class ChainedValidator extends ArrayList<Validator>
			implements Validator {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public boolean isValid(Object value) {
			for (Validator v : this) {
				if (!v.isValid(value))
					return false;
			}
			return true;
		}

		public void validate(Object value) throws InvalidValueException {
			for (Validator v : this)
				v.validate(value);
		}

	}

	public static class NewUser extends ChainedValidator {
		public NewUser() {
			add(new Email());
			add(new BeanExistsValidator(BeanSetManager.getManager(
					UserBean.class, null)));
		}
	}

	public static class Email extends EmailValidator {
		public Email() {
			super("Invalid email address");
		}
	}

	public static class SSID extends StringLengthValidator {
		public SSID() {
			super("SSID must be from 1 to 32 characters", 1, 32, false);
		}
	}

	public static class NonEmpty extends StringLengthValidator {
		public NonEmpty() {
			super("This field is required", 1, -1, false);
		}
	}
	
	public static class MACAddress extends RegexpValidator {

		public MACAddress() {
			super("(([0-9a-fA-F]){1,2}[-:]){5}([0-9a-fA-F]){1,2}",
					"Invalid MAC address format.");
		}
	}

	public static class IPAddress extends RegexpValidator {

		public IPAddress() {
			super("^(?:" + _255 + "\\.){3}" + _255 + "$",
					"Invalid ip address format.");
		}
	}
	
	
	
	
	
}
